<!-- 装箱入库 -->
<template>
	<view class="ku-content ku-flex-button-content">
		<!-- 	<view class="" v-if="fdocumentStatus==='A'">
			
		</view> -->
		<u-cell-group>
			<u-cell icon="file-text" :title="QRcodeNumber">
				<view slot="value" class="ku-display-flex">
					<u-button type="primary" icon="scan" @click="scanCodeClick" class="ku-margin-20-left"></u-button>
					<u-button type="error" icon="trash" @click="deletePackingClick"></u-button>

					<u-button type="warning" icon="checkmark" @click="approvalPackingClick"></u-button>
				</view>
			</u-cell>
		</u-cell-group>
		<view v-if="fdocumentStatus!=='A'" class="ku-card ku-margin-bottom-20">
			<view class="ku-card-head ku-display-flex ku-flex-space-between">
				单据/箱号：{{packingNumber}}
				<u-tag text="已审批" plain size="mini"></u-tag>
			</view>
		</view>

		<view class="ku-swipe-content">
			<u-swipe-action>
				<u-swipe-action-item :options="swipeOptions" v-for="item in packingClothRollList"
					@click='swipeActionItemClick(item)' :key="item.number">
					<view class="ku-card">
						<view class="ku-card-head ku-display-flex">
							<u-icon name="tags" color="#2979ff"></u-icon>布卷编码：{{item.number}}
						</view>
						<view class="ku-card-body">
							<view class="">
								<!-- 物料名称 -->
								物料名称：{{item.f_RYJF_WLMC}}
							</view>
							<view class="ku-xs-title">
								色LOT：<template v-if="item.f_RYJF_SELOT1"><text
										class="ku-text-warning">{{item.f_RYJF_SELOT1}}</text></template>;
								等级：<template v-if="item.f_RYJF_BJDJ">
									<!-- {{item.f_RYJF_BJDJ}} -->
								</template>; 类型：<template v-if="item.f_RYJF_BJLX">
									{{item.f_RYJF_BJLX}}
								</template>
							</view>
							<view class="ku-xs-title">
								包装单号：<template v-if="item.f_RYJF_BZDH">
									{{item.f_RYJF_BZDH}}
								</template>; 物料编码：<template v-if="item.f_RYJF_WLBM">
									{{item.f_RYJF_WLBM}}
								</template>
							</view>

							<view class="ku-xs-title">
								<text class="">花号：</text>
								<template v-if="item.ff100001">
									{{item.ff100001}}
								</template>；
								<text class="">色号：</text>
								<template v-if="item.ff100002">
									{{item.ff100002}}
								</template>；
								<text class="">门幅：</text>
								<template v-if="item.ff100003">
									{{item.ff100003}}
								</template>
							</view>
							<view class="ku-xs-title">
								<text class="">卷号：</text>
								<template v-if="item.name[0].value">
									{{item.name[0].value }}
								</template>；
								<text class="">米数：</text>
								<template v-if="item.f_RYJF_MIS">
									{{item.f_RYJF_MIS}}
								</template>；
								<text class="">码数：</text>
								<template v-if="item.f_RYJF_MAS">
									{{item.f_RYJF_MAS}}
								</template>
							</view>
						</view>
					</view>

				</u-swipe-action-item>
			</u-swipe-action>
		</view>

		<!-- 		<u-empty v-else mode="data" marginTop='40px'>
		</u-empty> -->
		<!-- <view class="ku-flex-body" v-if="fdocumentStatus==='A'"> -->
		<view class="ku-flex-body">
			<view class="ku-section">
				<view class="">
					<view class="">
						<u-text type="primary" :text="operationTypeText"></u-text>
						布卷数量：{{packingClothRollList.length}}/2000
					</view>
					<u-row justify="space-between" gutter="2" class="ku-mini-title">
						<u-col span="6">{{meterCount}}(M)</u-col>
						<u-col span="6">{{yardCount}}(Y)</u-col>
						<u-col span="6">{{kgCount}}(Kg)</u-col>
					</u-row>
				</view>
				<view class="ku-operation-button">
					<u-button type="primary" shape='circle' color="linear-gradient(to right,#235EFF, #235EFF)"
						:disabled="currentDisabledState" text="打包装箱" @click="packingBoxingClick"></u-button>
				</view>
			</view>
		</view>
		<u-modal :show="modalShow" :title="modalTitle" :content='modalContent' @confirm="confirmCloseModal"
			:showCancelButton='true' @cancel='modalShow=false' :closeOnClickOverlay="true"></u-modal>

		<u-notify ref="uNotify"></u-notify>

		<!-- 色段 提示 -->
		<u-modal :show="modalColorLotShow" :title="modalColorLotTitle" :content='modalColorLotContent'
			@confirm="confirmColorLotModal" :showCancelButton='true' @cancel='modalColorLotShow=false'
			:closeOnClickOverlay="true"></u-modal>


		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import store from "@/store";
	import {
		findIndex,
		filter,
		sumBy,
		forIn,
		uniqBy,
		cloneDeep
	} from "lodash";
	import {
		getColothRollInfoApi, // 获取布卷详情
		packingCreateBoxOrderApi, // 生成装箱单
		getPackingListSearchClothRollApi, // 根据装箱单fid查询布卷信息
		deletePackingBoxApi, // 根据内码fids删除装箱单
		approvalPackingApi, // 根据内码fids提交装箱单
		getPackingListSearchClothRollVerifyDuplicateApi, // 查询所有已经装箱布卷 验证重复问题
	} from "@/api/index.js";


	import {
		phoneCameraScanCode
	} from "@/utils/public.js";


	export default {
		data() {
			return {
				value6: '2',
				QRcodeNumber: '', // 二维码单号

				packingClothRollList: [], // 装箱材料清单
				currentDisabledState: true, // 打包装箱按钮禁用状态
				meterCount: 0, // 米数
				yardCount: 0, // 码数
				kgCount: 0, // 公斤总数


				packingType: 'add',
				packingFid: '',
				packingNumber: '',
				fdocumentStatus: 'A', // 审核状态

				f_RYJF_SCDDH: '', // 生产订单单号
				alreadyPackingClothRollList: [], // 所有已装箱布卷
				firstOneNumber: '', // 第一个布卷


				operationType: 'edit', // 操作类型，编辑，删除、审批
				operationTypeText: '新增',

				modalShow: false, // 提示框
				modalTitle: '操作提示',
				modalContent: '',

				colorLot: '', // 色 Lot 色段 -- 扫描的第一个布卷的色lot为依据，有不同色lot的要提示（不同色lot，是否拼箱），确认则允许拼箱，不允许则从该装箱单剔除该布卷
				modalColorLotShow: false,
				modalColorLotTitle: '',
				modalColorLotContent: '',

				temporaryFabricRoll: {}, // 临时布卷信息



				callScanDelayedClosureState: true, // 扫码延迟关闭

				swipeOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}]
			};
		},
		// 数据监听
		watch: {
			// 监听message数据的变化
			packingClothRollList(newVal, oldVal) {
				console.log(`数据监听----- packingClothRollList ----newVal---> `, newVal);
				if (newVal.length > 0) {
					let cloneDeepNewVal = cloneDeep(newVal)
					this.currentDisabledState = false;
					let newLength = cloneDeepNewVal.length;
					this.colorLot = cloneDeepNewVal[newLength - 1].f_RYJF_SELOT1; // 获取测色Lot
					this.meterCount = parseFloat(sumBy(cloneDeepNewVal, 'f_RYJF_MIS')).toFixed(1); // 米数
					this.yardCount = parseFloat(sumBy(cloneDeepNewVal, 'f_RYJF_MAS')).toFixed(1); // 码数
					this.kgCount = parseFloat(sumBy(cloneDeepNewVal, 'f_RYJF_ZHL')).toFixed(1); // 公斤总数

				} else {
					this.colorLot = '',
						this.currentDisabledState = true;
					this.meterCount = 0; // 米数
					this.yardCount = 0; // 码数
					this.kgCount = 0; // 公斤总数
				}
				// 在这里可以执行更多的逻辑
			},
			f_RYJF_SCDDH: {
				handler() {
					// 获取所有已装箱布卷
					this.getPackingListSearchClothRollVerifyDuplicateFun();
				},
				deep: true,
			},
		},
		/*
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			console.log('options-----装箱单详情----->', options);
			this.packingType = options.type;
			// 当前页面参数
			// this.initEmitMonitor();
			if (!this.$globalConfigs.IS_DEV) {
				window.callScanBack = this.callScanBack;
			}

			if (options.type === 'edit') {
				this.fdocumentStatus = options.fdocumentStatus; // 审核状态
				this.packingFid = options.packingFid;
				this.packingNumber = options.packingNumber;
				this.f_RYJF_SCDDH = options.f_RYJF_SCDDH;
				this.operationTypeText = '编辑：' + options.packingNumber;
				this.$nextTick(() => {
					this.getPackingListSearchClothRollFun();
				})
			} else {

			}
		},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {

		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		methods: {
			playAudio(url) {
				let audio = null;
				audio = uni.createInnerAudioContext();
				audio.src = url;
				// 确保音频播放在用户交互之后调用
				audio.autoplay = true;
				audio.play();
				audio.onPlay(() => {
					console.log('音频开始播放');
				});
				audio.onError((res) => {
					console.error('播放错误', res, url);
				});
			},
			// 扫码方法--公共
			async scanCodeClick() {
				console.log(this.$globalConfigs.IS_DEV);
				if (this.$globalConfigs.IS_DEV) {
					await phoneCameraScanCode(['barcode', 'qrCode'], true).then((res) => {
						console.log('扫码方法--公共--res-->', res);
						if (res.state === '0000') {
							this.QRcodeNumber = res.result;
							this.$nextTick(() => {
								this.getColothRollInfoFun();
							})
						} else {
							console.log('扫码--请重试！')
						}
					});

				} else {
					this.callScanNative();
				}

			},
			// 原生红外扫码
			callScanNative() {
				let _that = this;
				window.android.callScan();
				uni.showLoading({
					title: '扫码中...'
				});
			},
			//扫码数据回调
			callScanBack(res) {
				console.log('扫码数据回调----->', res);
				if (typeof res === 'string') {
					try {
						let result = {};
						result = JSON.parse(res);
						console.log('扫码数据回调----->', result);
						if (result.status_code === 200 && result.code) {
							this.QRcodeNumber = result.code;
							this.$nextTick(() => {
								this.getColothRollInfoFun();
							})
						} else if (result.status_code === 204) {
							this.$refs.uNotify.warning('请重新扫码！');
						}
					} catch (err) {
						//TODO handle the exception
						this.$refs.uNotify.warning('扫码错误请重新扫码！');
					}
				}
				uni.hideLoading();
			},
			// 根据装箱单fid查询布卷信息
			getPackingListSearchClothRollFun() {
				let _that = this;
				let params = {
					fid: this.packingFid,
					f_RYJF_SCDDH: this.f_RYJF_SCDDH,
				};
				getPackingListSearchClothRollApi(params).then((res) => {
					console.log('根据装箱单fid查询布卷信息--------->', res)
					// 0是下推失败 ，其它数字为下推成功，继续操作
					if (res.code === 200) {
						this.packingClothRollList = res.data;
					} else {
						this.$refs.uNotify.warning('未查询到布卷信息！')
					}
				})
			},
			/**
			 * @Description: 查询所有已装箱布卷
			 * 从第一个布卷中获取参数 f_RYJF_SCDDH 
			 * @Author: 王燕欣
			 * @Date: 2024-12-17 17:11
			 */
			async getPackingListSearchClothRollVerifyDuplicateFun() {
				let params = {
					f_RYJF_SCDDH: this.f_RYJF_SCDDH,
				};
				await getPackingListSearchClothRollVerifyDuplicateApi(params).then((res) => {
					console.log('查询所有已装箱布卷--------->', res)
					// 0是下推失败 ，其它数字为下推成功，继续操作
					if (res.code === 200) {
						this.alreadyPackingClothRollList = res.data;
						this.$nextTick(() => {
							this.handleFirstOne();
						})

					} else {

					}
				})

			},
			/**
			 * @Description: 处理第一个布卷，确认是否已经装箱了
			 * @Author: 王燕欣
			 * @Date: 2024-12-19 17:01
			 */
			handleFirstOne() {
				let _that = this;
				let findIndexAlready = findIndex(this.alreadyPackingClothRollList, (itemL) => {
					return itemL == this.firstOneNumber
				})
				if (findIndexAlready > -1) {
					this.packingClothRollList = [];
					this.f_RYJF_SCDDH = '';
					this.$refs.uNotify.warning('重复装箱!');
					// 播放重复装箱声音
					setTimeout(() => {
						_that.playAudio('/static/sounds/repeated_packing.mp3');
					}, 500);
					return
				}
			},

			// 需求是，第一个布卷不做验证，第二个布卷开始进行验证，
			// 1、是否在此箱中已存在
			// 2、是否已经装在其它箱子
			// 3、不同生产单号不能装箱
			// 获取布卷信息详情--王杰超 
			getColothRollInfoFun() {
				let _that = this;
				// 判断数据中是否有此布卷，如果没有则加入数组中如果有则提示用户
				let findIndexNumber = findIndex(this.packingClothRollList, (itemK) => {
					return itemK.number === this.QRcodeNumber
				})
				if (findIndexNumber > -1) {
					// 已添加到了箱子中
					_that.$refs.uNotify.warning('已在此箱中！');
					// 播放重复扫码声音
					setTimeout(() => {
						_that.playAudio('/static/sounds/repeat.mp3');
					}, 500);
					return
				};

				let findIndexAlready = findIndex(this.alreadyPackingClothRollList, (itemL) => {
					return itemL == this.QRcodeNumber
				})
				// console.log('是否已装箱过-----',findIndexAlready);
				if (findIndexAlready > -1) {
					this.$refs.uNotify.warning('重复装箱!');
					// 播放重复装箱声音
					setTimeout(() => {
						_that.playAudio('/static/sounds/repeated_packing.mp3');
					}, 500);
					return
				}

				// 播放扫码声音
				this.playAudio('/static/sounds/di.mp3');
				let params = {
					number: this.QRcodeNumber,
				};
				getColothRollInfoApi(params).then((res) => {
					console.log('获取布卷信息详情--------->', res)
					// 0是下推失败 ，其它数字为下推成功，继续操作
					if (res.code === 200 && res.data) {
						if (!this.f_RYJF_SCDDH) {
							this.f_RYJF_SCDDH = res.data.f_RYJF_SCDDH; // 赋值用于查询所有
							this.firstOneNumber = res.data.number;
						}

						console.log('当前箱子已--装箱材料清单--', this.packingClothRollList);
						if (this.packingClothRollList.length < 2000) {
							if (this.packingClothRollList.length > 0) {
								if (this.packingClothRollList[0].f_RYJF_XSDDH !== res.data.f_RYJF_XSDDH) {
									this.$refs.uNotify.warning('不同生产订单号的布卷不能放在同一装箱单里!');
									setTimeout(() => {
										_that.playAudio('/static/sounds/different_order_numbers.mp3');
									}, 500);
									return
								}
							};
							this.QRcodeNumber = '';
							// 扫描的第一个布卷的色lot为依据，有不同色lot的要提示（不同色lot，是否拼箱），确认则允许拼箱，不允许则从该装箱单剔除该布卷

							if (this.colorLot && this.colorLot !== res.data.f_RYJF_SELOT1) {
								this.modalColorLotShow = true;
								this.modalColorLotTitle = '提示';
								this.modalColorLotContent =
									`当前布卷色Lot：${res.data.f_RYJF_SELOT1}与第一布卷色Lot:${this.colorLot}不同是否拼箱！`;
								this.temporaryFabricRoll = res.data;
							} else {
								this.packingClothRollList.unshift(res.data);
								this.$refs.uNotify.success('操作成功！')
							}
						} else {
							this.$refs.uNotify.warning('单箱子最多2000卷')
						}

					} else {
						this.$refs.uNotify.warning('未查询到布卷信息！');
						setTimeout(() => {
							_that.playAudio('/static/sounds/not_found.mp3');
						}, 500);
						return
					}
				})
			},
			// 不同色Lot 是否确认装箱在一起。
			confirmColorLotModal() {
				this.modalColorLotShow = false;
				this.modalColorLotTitle = '';
				this.modalColorLotContent = '';
				this.packingClothRollList.unshift(this.temporaryFabricRoll);
				this.$refs.uNotify.success('操作成功！')
			},

			// 滑块--布卷---操作-删除等
			swipeActionItemClick(e) {
				console.log('滑块操作-删除等------->', e);
				this.packingClothRollList = filter(this.packingClothRollList, (itemK) => {
					return itemK.number !== e.number;
				});
				if (this.packingClothRollList.length === 0) {
					this.f_RYJF_SCDDH = '';
				}
			},

			// 删除装箱单
			deletePackingClick() {
				this.modalTitle = '确认删除此装箱单？';
				this.modalShow = true;
				this.operationType = 'delete';
			},

			//  打包装箱
			packingBoxingClick() {
				this.modalTitle = '确认装箱?'
				// 筛选 色Lot
				let screenColorLot = uniqBy(this.packingClothRollList, 'f_RYJF_SELOT1');
				if (screenColorLot.length > 1) {
					let colorLotList = [];
					for (let i = 0; i < screenColorLot.length; i++) {
						let itemI = screenColorLot[i];
						if (itemI.f_RYJF_SELOT1) {
							colorLotList.push(itemI.f_RYJF_SELOT1);
						}
					}
					this.modalContent = `该装箱单存在多个色Lot：${colorLotList} 是否拼箱!`;
				}

				this.modalShow = true;
				this.operationType = 'edit'
			},
			// 审批
			approvalPackingClick() {
				this.modalTitle = '确认审批此装箱单?';
				this.modalShow = true;
				this.operationType = 'approval'
			},

			// 确认关闭弹出框
			async confirmCloseModal() {
				this.modalShow = false;
				console.log('打包装箱----------->', this.packingClothRollList);
				console.log('打包装箱----- operationType ------>', this.operationType);

				if (this.operationType == 'edit') {

					let fabricRollNumberList = [];
					for (var i = 0; i < this.packingClothRollList.length; i++) {
						let itemI = this.packingClothRollList[i];
						fabricRollNumberList.push(itemI.number);
					}
					if (this.packingType === 'add') {
						let params = {
							numbers: fabricRollNumberList,
						};
						console.log('打包装箱--- params -->', params);
						await packingCreateBoxOrderApi(params).then((res) => {
							console.log('打包装箱- add--res-->', res);
							if (res.code === 200) {
								this.$refs.uToast.show({
									type: 'success',
									title: '操作提示',
									message: "操作成功",
									complete() {
										uni.navigateBack();
									}
								})
							} else {
								this.$refs.uNotify.warning(res.message)
							}
						})
					} else if (this.packingType === 'edit' && this.packingFid && this.packingNumber) {
						let params = {
							numbers: fabricRollNumberList,
							number: this.packingNumber,
							fid: this.packingFid
						};
						console.log('打包装箱--- params -->', params);
						await packingCreateBoxOrderApi(params).then((res) => {
							console.log('打包装箱- edit --res-->', res);
							if (res.code === 200) {
								this.$refs.uToast.show({
									type: 'success',
									title: '操作提示',
									message: "操作成功",
									complete() {
										uni.navigateBack();
									}
								})
							} else {
								this.$refs.uNotify.warning(res.message)
							}
						})
					} else {

					}
				} else if (this.operationType == 'delete') {
					let params = {
						fids: this.packingFid,
					};
					console.log('根据内码fids删除装箱单--- params -->', params);
					await deletePackingBoxApi(params).then((res) => {
						console.log('根据内码fids删除装箱单- delete --res-->', res);
						if (res.code === 200) {
							this.$refs.uToast.show({
								type: 'success',
								title: '操作提示',
								message: "操作成功",
								complete() {
									uni.navigateBack();
								}
							})
						} else {
							this.$refs.uNotify.warning(res.message)
						}
					})
				} else if (this.operationType == 'approval') {
					let params = {
						fids: this.packingFid,
					};
					console.log('提交装箱单 审批- approval--- params -->', params);
					await approvalPackingApi(params).then((res) => {
						console.log('提交装箱单 审批- approval --res-->', res);
						if (res.code === 200) {
							this.$refs.uToast.show({
								type: 'success',
								title: '操作提示',
								message: "操作成功",
								complete() {
									uni.navigateBack();
								}
							})
						} else {
							this.$refs.uNotify.warning(res.message)
						}
					})
				}
			},
		},
		/**
		   * 
		''   * 下拉刷新
		   */
		onPullDownRefresh() {

		},

		/**
		 * 分享当前页面
		 */
		onShareAppMessage() {},

		/**
		 * 分享到朋友圈
		 * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
		 * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
		 */
		onShareTimeline() {},
	}
</script>

<style lang="scss">

</style>